package com.chao.demo.utils.desensitization;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
//这个是序列化器
public class DesensitionJsonSerializable extends JsonSerializer<String> implements ContextualSerializer {
    private DesensitizationStrategy strategy;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }
        gen.writeString(strategy.desensitize(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        Desensitization annotation = property.getAnnotation(Desensitization.class);
        if (annotation != null && String.class.equals(property.getType().getRawClass())) {
            this.strategy = annotation.value();
            return this; // 返回当前实例（已配置策略）
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
